<template>
  <div class="wrapper">
    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="12">
        <div class="label">姓名</div>
        <el-input placeholder="姓名" size="small" v-model="paramsState.name" style="width: 200px">
        </el-input>
        <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-search"
                   @click="search">搜索
        </el-button>
        <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-delete"
                   @click="deleteList">批量删除
        </el-button>
        <el-button style="margin-left: 10px" type="primary" size="small" icon="el-icon-download"
                   @click="downloadList">批量下载
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table :data="tableData" v-loading="listLoading" border @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          fixed
          align="center"
          width="45">
      </el-table-column>
      <el-table-column show-overflow-tooltip v-for="field in fields" :key="field.prop" :prop="field.prop"
                       :label="field.label"
                       :width="field.width" :align="field.align">
        <template v-slot="{ row }">
          <el-avatar style="background: transparent" v-if="field.prop == 'FacePhoto'" shape="square" :size="50"
                     fit="fill"
                     :src="row[field.prop]"></el-avatar>
          <el-select v-else-if="field.prop == 'IsTraining' || field.prop == 'IsPreTraining'" style="width: 80px;"
                     size="small" v-model="row[field.prop]" placeholder="请选择"
                     @change="PropsSelect($event,row,field.prop)">
            <el-option label="是" value="是"/>
            <el-option label="否" value="否"/>
          </el-select>
          <span v-else>{{ row[field.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="420" align="center" fixed="right">
        <template v-slot="{ row }">
          <el-button type="text" title="检查图片" @click="lookImages(row)">检查图片</el-button>
          <el-button type="text" title="文档下载" @click="downloadFile(row.wordUrl)">文档下载</el-button>
          <el-button type="text" :loading="row.loading"
                     @click="PropsSelect(row.IsTraining == '是' ? '否' :'是',row,'IsTraining')">
            {{ row.IsTraining == "是" ? "关闭" : "开通" }}日常培训
          </el-button>
          <el-button type="text" :loading="row.loading"
                     @click="PropsSelect(row.IsPreTraining == '是' ? '否' :'是',row,'IsPreTraining')">
            {{ row.IsPreTraining == "是" ? "关闭" : "开通" }}岗前培训
          </el-button>
          <el-button type="text" title="编辑" @click="handle(row)">编辑</el-button>
          <el-button type="text" title="删除" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination :current-page="paramsState.startpoint" :page-size="paramsState.nums" :total="paramsState.total"
                   :page-sizes="[5, 10, 20, 30]" style="padding: 20px 0"
                   layout="prev, pager, next, jumper, ->, sizes, total"
                   @current-change="currentChange" @size-change="sizeChange"/>

    <!-- 查看 or 编辑框-->
    <el-dialog :title="findData.readonly ? '查看' : '编辑'" width="800px" z-index="100" :visible.sync="Visible" @closed="resetDialog">
      <el-form v-loading="loading" size="small" class="formRow" label-position="top">
        <el-row :gutter="12">
          <el-col :span="3">
            <el-form-item label="头像" prop="FacePhoto">
              <div style="cursor: pointer" @click="editImage">
                <el-avatar shape="square" style="background: transparent" :size="50" fit="fill"
                           :src="findData.FacePhoto"></el-avatar>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="姓名" prop="Name">
              <el-input style="margin-top: 10px" v-model="findData.Name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="身份证号" prop="IDCard">
              <el-input style="margin-top: 10px" v-model="findData.IDCard"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年龄" prop="Age">
              <el-input-number style="margin-top: 10px" class="w100" v-model="findData.Age"
                               controls-position="right" :min="1" :max="200"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="5">
            <el-form-item label="性别" prop="Gender">
              <el-radio-group class="w100" v-model="findData.Gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="出生年月" prop="Birthday">
              <el-date-picker class="w100" v-model="findData.Birthday" type="date"
                              value-format="yyyy-MM-dd" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="学历" prop="Education">
              <el-select class="w100" v-model="findData.Education" clearable placeholder="请选择">
                <el-option v-for="item in educationList" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="从业资格证号" prop="QualificationCertificateNumber">
              <el-input class="w100" v-model="findData.QualificationCertificateNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="资格证有效期" prop="QualificationCertificateValidity">
              <el-date-picker class="w100" v-model="findData.QualificationCertificateValidity" type="date"
                              value-format="yyyy-MM-dd" placeholder="选择日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家庭住址" prop="Address">
              <el-input class="w100" v-model="findData.Address"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="本人联系电话" prop="ContactNumber">
              <el-input class="w100" v-model="findData.ContactNumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="家属姓名" prop="FamilyContactName">
              <el-input class="w100" v-model="findData.FamilyContactName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家属联系电话" prop="FamilyContactNumber">
              <el-input class="w100" v-model="findData.FamilyContactNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否有重大以上交通事故" prop="HasMajorAccident">
              <el-radio-group v-model="findData.HasMajorAccident">
                <el-radio label="是">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="24">
            <el-form-item label="工作简历" prop="Resume">
              <el-input type="textarea" :rows="3" class="w100" v-model="findData.Resume"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="安全责任开始时间" prop="SafetyResponsibilityStartDate">
              <el-date-picker class="w100" v-model="findData.SafetyResponsibilityStartDate" type="date"
                              value-format="yyyy-MM-dd" placeholder="选择日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="安全责任结束时间" prop="SafetyResponsibilityEndDate">
              <el-date-picker class="w100" v-model="findData.SafetyResponsibilityEndDate" type="date"
                              value-format="yyyy-MM-dd" placeholder="选择日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同有效期" prop="ContractValidityDate">
              <el-date-picker class="w100" v-model="findData.ContractValidityDate" type="date"
                              value-format="yyyy-MM-dd" placeholder="选择日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="是否开通日常培训" prop="IsTraining">
              <el-radio-group v-model="findData.IsTraining">
                <el-radio label="是">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否开通岗前培训" prop="IsPreTraining">
              <el-radio-group v-model="findData.IsPreTraining">
                <el-radio label="是">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资格证编号" prop="ZiGeZhengID">
              <el-input class="w100" v-model="findData.ZiGeZhengID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证正面" prop="IDCardFront">
              <upload v-model="findData.IDCardFront"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证反面" prop="IDCardBack">
              <upload v-model="findData.IDCardBack"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="从业资格证" prop="QualificationCertificatePhotos">
              <uploads v-model="findData.QualificationCertificatePhotos"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签名" prop="Signature">
              <upload v-model="findData.Signature"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button v-if="!findData.readonly" :loading="loading" type="primary" @click="onSubmit">{{ loading ? "提交中..." : "提交" }}</el-button>
      </div>
    </el-dialog>


    <el-dialog title="检查图片" width="800px" :visible.sync="imagesVisible" @closed="resetDialog">
      <el-form size="small" class="formImages" label-position="top" v-if="imagesVisible">
        <el-form-item label="身份证">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-image class="image" :src="findData.IDCardFront" lazy :preview-src-list="[findData.IDCardFront]"
                        fit="cover">
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </el-col>
            <el-col :span="12">
              <el-image class="image" :src="findData.IDCardBack" lazy :preview-src-list="[findData.IDCardBack]"
                        fit="cover">
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="从业资格证">
          <el-row :gutter="15">
            <el-col :span="12" v-for="(image, index) in findData.QualificationCertificatePhotos" :key="index">
              <el-image class="image" :src="image" lazy :preview-src-list="[image]" fit="cover">
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="签字">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-image class="image" :src="findData.Signature" lazy
                        :preview-src-list="[findData.Signature]" fit="cover">
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <ImgCutter ref="imgCutterModal" @cutDown="cutDown" :crossOrigin="true" :showChooseBtn="false">
      <template #open>
        <span></span>
      </template>
    </ImgCutter>
  </div>
</template>

<script>
import {query_escort, add_escort, delete_escort, modify_escort} from "@/api"
import moment from "moment"
import {exportExcel, downloadFile, uploadImage} from "@/utils"
import upload from "./components/upload.vue"
import uploads from "./components/uploads.vue"
import ImgCutter from 'vue-img-cutter';

export default {
  name: "escortList",
  components: {
    ImgCutter,
    upload, uploads
  },
  data() {
    return {
      // 加载
      listLoading: false,
      // 详情弹窗
      Visible: false,
      // 检查图片
      imagesVisible: false,
      updateVisible: false,
      // 搜索用户相关
      paramsState: {
        name: '',
        startpoint: 1,
        nums: 10,
        total: 0
      },
      // 用户列表相关
      tableData: [],
      // 详情加载中
      loading: false,
      type: 'rgxd',

      // 操作的数据信息
      findData: {
        id: '',
        Age: '',
        Gender: '',
        Birthday: '',
        FacePhoto: '',
        Education: '',
        QualificationCertificateNumber: '',
        QualificationCertificatePhotos: '',
        QualificationCertificateValidity: '',
        Address: '',
        ContactNumber: '',
        FamilyContactName: '',
        FamilyContactNumber: '',
        HasMajorAccident: '',
        Resume: '',
        IDCardFront: '',
        IDCardBack: '',
        SafetyResponsibilityStartDate: '',
        SafetyResponsibilityEndDate: '',
        ContractValidityDate: '',
        Signature: '',
        IsTraining: '',
        IsPreTraining: '',
        ZiGeZhengID: ''
      },
      fields: [
        {label: '姓名', prop: 'Name', width: '', align: 'center'},
        {label: '身份证号码', prop: 'IDCard', width: '130', align: 'center'},
        {label: '年龄', prop: 'Age', width: '', align: 'center'},
        {label: '性别', prop: 'Gender', width: '', align: 'center'},
        {label: '出生日期', prop: 'Birthday', width: '180', align: 'center'},
        {label: '头像', prop: 'FacePhoto', width: '80', align: 'center'},
        {label: '学历', prop: 'Education', width: '', align: 'center'},
        {label: '资格证编号', prop: 'ZiGeZhengID', width: '150', align: 'center'},
        {label: '从业资格证号', prop: 'QualificationCertificateNumber', width: '150', align: 'center'},
        {label: '资格证有效期', prop: 'QualificationCertificateValidity', width: '200', align: 'center'},
        {label: '本人联系电话', prop: 'ContactNumber', width: '180', align: 'center'},
        {label: '家属姓名', prop: 'FamilyContactName', width: '', align: 'center'},
        {label: '家属联系电话', prop: 'FamilyContactNumber', width: '180', align: 'center'},
        {label: '是否有重大以上交通事故', prop: 'HasMajorAccident', width: '180', align: 'center'},
        {label: '安全责任开始时间', prop: 'SafetyResponsibilityStartDate', width: '180', align: 'center'},
        {label: '安全责任结束时间', prop: 'SafetyResponsibilityEndDate', width: '180', align: 'center'},
        {label: '合同有效期', prop: 'ContractValidityDate', width: '180', align: 'center'},
        {label: '是否开通日常培训', prop: 'IsTraining', width: '150', align: 'center'},
        {label: '是否开通岗前培训', prop: 'IsPreTraining', width: '150', align: 'center'}
      ],
      educationList: [
        "小学",
        "初中",
        "高中",
        "大专",
        "本科",
        "硕士",
        "博士"
      ],
      multipleSelection: []
    }
  },
  methods: {
    downloadFile,
    downloadList(){
      const length = this.multipleSelection.length;
      if (length <= 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        });
        return;
      }

      this.$confirm(`确定要下载选中的${length}条数据吗`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.multipleSelection.forEach(item => {
          downloadFile(item.wordUrl);
        })
      })
    },
    editImage() {
      let src = this.findData.FacePhoto;
      let name = decodeURIComponent(src.split('=').pop());
      this.$refs.imgCutterModal.handleOpen({
        name: name,
        src: src
      });
    },
    // 图片裁剪完成后触发
    cutDown(e) {
      uploadImage(e.file, (path) => {
        this.findData.FacePhoto = path;
      })
    },
    // 批量删除
    deleteList() {
      const length = this.multipleSelection.length;
      if (length <= 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        });
        return;
      }
      this.$confirm(`确定要将选中的${length}条数据删除吗`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let array = [];
        this.multipleSelection.forEach(async (item) => {
          array.push(await delete_escort({
            id: item.ID
          }))
        })
        Promise.all(array).then(() => {
          console.log("全部执行完成")
          this.$message({
            type: 'success',
            message: `批量删除成功!`
          });
          this.multipleSelection = [];
          this.getList();
        })
      })
    },
    // 表格选择事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 表格插槽选择事件
    PropsSelect(value, row, name) {
      row.loading = true;
      modify_escort({
        ...row,
        id: row.ID,
        [name]: value
      }).then(result => {
        this.$message.success(result.msg);
        this.getList()
      })
    },
    dateFormat(date) {
      let expirationDate = moment(date)
      // 获取当前时间
      let now = moment()
      // 计算时间差
      let duration = moment.duration(expirationDate.diff(now)).days()
      if (duration < 0) {
        return "已过期"
      } else {
        return duration + "天"
      }
    },
    change(file) {
      let _this = this
      console.log(file.raw)
      let reader = new FileReader()
      reader.onload = function (event) {
        let base64 = event.target.result
        _this.findData.headimg = base64
      }
      reader.readAsDataURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const types = ['image/jpeg', 'image/png']
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!types.includes(file.type)) {
        this.$message.error('上传头像图片只能是 JPG 和 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    // 获取用户列表数据
    async getList() {
      this.listLoading = true
      try {
        let params = {
          ...this.paramsState
        }

        delete params.time
        delete params.total

        let result = await query_escort(params)
        this.tableData = result.data
        this.listLoading = false

        this.paramsState.total = result.data.total
        console.log(result.data)
      } catch (error) {
        this.listLoading = false
        this.$message.error("获取列表失败，请重试")
      }
    },
    // 根据用户输入进行查询
    search() {
      this.paramsState.startpoint = 1
      this.getList()
    },
    sizeChange(e) {
      this.paramsState.nums = e
      this.getList()
    },
    currentChange(e) {
      this.paramsState.startpoint = e
      this.getList()
    },
    resetDialog() {
      this.findData = {}
    },
    // 保存
    onSubmit() {
      this.loading = true;
      let params = {
        ...this.findData,
        id: this.findData.ID
      }
      params.QualificationCertificatePhotos = params.QualificationCertificatePhotos.join("|")

      console.log(params, "提交参数")

      modify_escort(params).then(result => {
        console.log(result, "处理订单")
        this.$message.success(result.msg)
        this.getList()
        this.Visible = false
        this.loading = false
      }).catch(()=>{
        this.loading = false
      })
    },
    // 检查图片
    lookImages(row) {
      console.log(row)
      this.imagesVisible = true
      this.findData = {
        ...row,
        QualificationCertificatePhotos: row.QualificationCertificatePhotos.split("|"),

      }
    },
    // 显示详情
    handle(row, readonly = false) {
      let params = {
        ...row,
        QualificationCertificatePhotos: row.QualificationCertificatePhotos.split("|"),
        readonly
      }
      this.findData = params
      this.Visible = true
    },
    // 操作
    update(row) {
      this.findData = {
        id: row.id
      }
      this.updateVisible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log('row: ', row)
        delete_escort({id: row.ID}).then(() => {
          this.$message({
            type: 'success', message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {

      })
    }
  },
  async mounted() {
    await this.getList()
  }
}
</script>

<style lang="scss" scoped>
.table-avatar {
  width: 40px;
  height: 40px;
}

::v-deep .image-table-slot {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #eee;
}

.wrapper {
  margin: 20px;

  .image {
    width: 100%;
    max-height: 250px;
  }

  .label {
    font-size: 14px;
    color: #333;
    padding-bottom: 10px;
  }
}

::v-deep .el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

::v-deep .el-dialog__body {
  padding: 10px 20px;
}

.formRow {

  &.disabled {
    pointer-events: none;
  }


  .el-col {
    padding: 8px 0;

    .label {
      font-weight: 500;
      margin-right: 10px;
      color: #444;
    }

    .headimg_view {
      margin-left: 50%;
      transform: translateX(-50%);
      overflow: hidden;

      .avatar {
        width: 120px;
        height: 120px;
        font-size: 0;
      }

      ::v-deep .image-slot {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        background-color: #eee;

        .iocn {
          font-size: 20px;
        }

        span {
          font-size: 14px;
        }
      }
    }
  }

  .sourceList {
    .item {
      padding: 10px;
      background-color: #f8f8f8;
      border-bottom: 1px solid #ddd;

      &:last-child {
        border-bottom: 0;
      }

      .box {
        padding: 5px 0;
        display: flex;

        .label {
          color: #666;
          padding-right: 20px;
        }
      }
    }
  }
}

.dataList {
  margin-bottom: 20px;

  .desc {
    margin-top: 10px;
    color: #888;
  }

  .dataTitle {
    font-weight: 500;
    color: #333;
  }
}

//::v-deep .el-form-item__label {
//  width: 100%;
//}

.flex {
  display: flex;

  span {
    b {
      color: #f46162;
    }
  }

  &.between {
    justify-content: space-between;
  }
}
</style>
